import router, { asyncRoutes } from './router'
/* import {
  tenantLayout,
  // uiScanRoutes,
  tenantRoutes,
  accountRoutes
} from '@/router/modules/adminManage' */
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
  getToken,
  setToken,
  setTokenType,
  setRefreshToken
} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { getUrlParam } from '@/utils'
import { getTokenByTranCode } from '@/api/user'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

let flag = true
router.beforeEach(async(to, from, next) => {
  const code = getUrlParam('token')
  if (code && flag) {
    flag = false
    try {
      const { data } = await getTokenByTranCode(code)
      setToken(data.access_token)
      setTokenType('bearer')
      setRefreshToken(data.refresh_token)
      sessionStorage.setItem('hide-toolbar', getUrlParam('hide-toolbar') || '')
    } finally {
      const shortURL = self.location.href.split('?')[0]
      window.history.replaceState({}, '', shortURL)
    }
  }

  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const { roles } = store.getters
      const hasRoles = roles && roles.length > 0
      const ADMIN = 'ADMIN,MT_ADMIN'
      if (hasRoles) {
        if (to.path !== '/login' && !roles.some(item => ADMIN.includes(item.roleId))) {
          // 获取当前页面的 ui 资源授权列表
          await store.dispatch('permission/fetchUserUiPermission', to.path)
        }
        next()
      } else {
        try {
          // const { roles } = await store.dispatch('user/getInfo')
          // const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
          // store.commit('user/SET_ROLES', ['admin'])
          // router.addRoutes(accessRoutes)
          const { data: userInfo } = await store.dispatch('user/getUserInfo')
          const { data: accountInfo } = await store.dispatch('user/fetchUserTenantAccounts')
          // 中央认证 租户管理员角色,显示所有路由表
          if (userInfo.roles.some(item => ADMIN.includes(item.roleId)) || accountInfo.accountAdmin) {
            await store.dispatch('permission/judgeAdminRoleMenuList')
            /* tenantLayout.children = []
            // 多租户系统是本地注册时,则有账套管理功能
            accountInfo.selfRegister && tenantLayout.children.push(tenantRoutes[0])
            // 账套管理员,拥有资源扫描权限
            accountInfo.accountAdmin && tenantLayout.children.push(tenantRoutes[1])
            // 当超管拥有账套管理员角色
            tenantLayout.children.push(...accountRoutes)
            // 判断当前路由表中是否已存在授权管理菜单,如果不存在,则添加
            if (asyncRoutes.map(item => item.path).every(item => item !== tenantLayout.path) && tenantLayout.children.length > 0) {
              const len = asyncRoutes.length
              asyncRoutes.splice(len - 1, 0, tenantLayout)
            }
            store.commit('permission/SET_ROUTES', asyncRoutes)
            router.addRoutes(asyncRoutes) */
            next({ ...to, replace: true })
          } else { // 普通角色,查询后台授权路由列表
            if (accountInfo.tenantId && accountInfo.tenantId !== null) {
              const finalRoute = await store.dispatch('permission/fetchUserMenuPermission')
              const { access_list } = store.getters
              router.addRoutes(finalRoute)
              if (access_list.length && access_list.includes(to.path.substring(1))) {
                next({ ...to, replace: true })
              } else {
                next('/')
              }
            } else {
              next('/')
            }
          }
          NProgress.done()
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          console.error(error)
          let info = ''
          if (typeof error === 'string') {
            info = error
          } else {
            info = error.message || '某些地方出问题啦!'
          }
          Message.error(info)
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
